package com.blue.basic.data.blf_test;

/**
 * 便利峰面试题：数组
 *
 * @author liulei, lei.liu@htouhui.com
 * @version 1.0
 */
public class Array<E> {
    E[] data;
    int size;

    public Array(int capacity) {
        this.data = (E[]) new Object[capacity];
        this.size = 0;
    }

    public E get(int index) {
        return data[index];
    }

    public boolean isEmpty() {
        return this.size == 0;
    }

    public int getSize() {
        return this.size;
    }

    public void add(int index, E e) {
        if (index < 0 || index > data.length) {
            throw new IllegalArgumentException("index is out of range 0 to " + data.length);
        }
        if (size == data.length) {
            resize(2 * data.length);
        }
        for (int i = size - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        data[index] = e;
        size++;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < data.length; i++) {
            newData[i] = data[i];
        }
        data = newData;
    }

    public void addFirst(E e) {
        add(0, e);
    }

    public void addLast(E e) {
        add(size, e);
    }

    public void remove(int index) {
        if (isEmpty()) {
            throw new IllegalArgumentException("empty array");
        }
        if (index < 0 || index > data.length) {
            throw new IllegalArgumentException("index is out of range");
        }
        for (int i = index; i < size; i++) {
            data[i] = data[i + 1];
        }
        size--;
    }

    public void removeFirst() {
        remove(0);
    }

    public void removeLast() {
        remove(size - 1);
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        for (E e : data) {
            stringBuilder.append(e + ",");
        }
        return stringBuilder.toString();
    }

    public void swap(int srcIndex, int tarIndex) {
        E tmp = data[tarIndex];
        data[tarIndex] = data[srcIndex];
        data[srcIndex] = tmp;
    }

    public static void main(String[] args) {
        Array<Integer> array = new Array<>(4);
        array.addFirst(0);
        array.addFirst(1);
        array.addFirst(2);
        array.addFirst(3);
        array.addFirst(4);
        array.removeLast();
        System.out.println(array);
    }
}
